package handler;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import model.MethodInfo;
import model.ServerInfo;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Slf4j
public class WebRestClient implements RestHandler {
    private WebClient client;

    @Override
    public Object invoke(MethodInfo methodInfo) {
        WebClient.RequestBodySpec requestBodySpec = this.client.method(methodInfo.getMethod())
                .uri(methodInfo.getUri(), methodInfo.getParams())
                .contentType(MediaType.APPLICATION_JSON);

        if (methodInfo.getBody() != null) {
            requestBodySpec.body(methodInfo.getBody(), methodInfo.getBodyElementType());
        }

        WebClient.ResponseSpec responseSpec = requestBodySpec.retrieve();
        responseSpec.onStatus((httpStatus -> {
            return httpStatus.value() != 200;
        }), resp -> {
            log.error(methodInfo.getUri() + resp.statusCode().getReasonPhrase());
            return Mono.empty();
        });
        if (methodInfo.isReturnFlux()) {
            return responseSpec.bodyToFlux(methodInfo.getReturnElementType());
        }
        return responseSpec.bodyToMono(methodInfo.getReturnElementType());
    }

    @Override
    public void init(ServerInfo serverInfo) {
        this.client = WebClient.create(serverInfo.getUrl());
    }
}
